package com.slkj.shilixiaoyuanapp.ui.user.activity;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.TeacherInfoEntity;
import com.slkj.shilixiaoyuanapp.entity.UserEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.StateLayout;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.ObservableSource;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHANGE_NIKENAME_FINSH;

@ActivityInfo(layout = R.layout.personal_information_activity, title = "个人信息")
public class PersonalInformationActivity extends BaseActivity {
    @BindView(R.id.img_head)
    CircleImageView imgHead;
    @BindView(R.id.tv_bj)
    TextView tvBj;
    @BindView(R.id.tv_nc)
    TextView tvNc;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_zc)
    TextView tvZc;
    @BindView(R.id.tv_xl)
    TextView tvXl;
    @BindView(R.id.tv_school)
    TextView tvSchool;
    @BindView(R.id.statelayout)
    StateLayout statelayout;
    public TakePictureUtils takePictureUtils;

    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        getInfo();
        statelayout.setOnReLoadListener(this::getInfo);
    }

    private void getInfo() {
        HttpHeper.get().userService().getUserInfo()
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<TeacherInfoEntity>(statelayout) {
                    @Override
                    public void onCallBackSuccess(TeacherInfoEntity data) {
                        Glide.with(PersonalInformationActivity.this).load(data.getHeadImg()).into(imgHead);
                        tvBj.setText(data.getUWorkNumber());
                        tvNc.setText(data.getUNickName());
                        tvPhone.setText(data.getUPhone());
                        if (!data.getTitle().isEmpty()) {
                            tvZc.setText(data.getTitle().get(0));
                        }
                        tvXl.setText(data.getUEducation());
                        tvSchool.setText(data.getUGraduateSchool());

                    }
                });
    }

    /**
     * 修改昵称
     */
    @OnClick(R.id.tv_nc)
    void changeNc() {
        startActivity(ChangeNickNameActivity.class);
    }
    @Recipient(tag = CHANGE_NIKENAME_FINSH)
    void  changeNameBack(String name){
        tvNc.setText(name);
        UserEntity userEntity = UserRequest.getInstance().getUser();
        userEntity.getUser().setUNickName(name);
        UserRequest.getInstance().setUser(userEntity);
    }

    /**
     * 修改头像
     */
    @OnClick(R.id.img_head)
    void changeHead() {
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {

                upNewHead(outFile.getPath());
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });
        showPhotoDialog();
    }

    /**
     * 上传新头像
     *
     * @param path
     */
    private void upNewHead(String path) {
        List<String> picPaths = new ArrayList<>();
        picPaths.add(path);
        UpdataFileUtil.UpImgObservable("head", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        return HttpHeper.get().userService().updateHeadImg(StringUtils.listToString(result));
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true,PersonalInformationActivity.this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        Glide.with(PersonalInformationActivity.this).load(data).into(imgHead);
                        LoadSuccessAndFailDialog.showSuccess(PersonalInformationActivity.this,data);
                        UserEntity userEntity = UserRequest.getInstance().getUser();
                        userEntity.getUser().setHeadImg(data);
                        UserRequest.getInstance().setUser(userEntity);
                    }
                });
    }

    public void showPhotoDialog() {
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }
            @Override
            public void chosePhoto() {
                takePictureUtils.getByAlbum();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);

    }
}
